using System;
using Microsoft.Extensions.Caching.Memory;

namespace Catastrophe.Initialize.IOCProvier
{
	public class LocalCacheProvider : ICacheProvider, IDisposable
	{
		public const int DEFAULT_EXPIRE_TIME = 10;

		private static MemoryCache MemCache = new MemoryCache(new MemoryCacheOptions());

		public T GetCache<T>(string key)
		{
			if (key != null && LocalCacheProvider.MemCache.TryGetValue(key, out var result))
			{
				return (T)result;
			}
			return default(T);
		}

		public void SetCache<T>(string key, T value, TimeSpan? expireTime = null)
		{
			if (key != null)
			{
				MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();
				if (expireTime.HasValue)
				{
					options.SetAbsoluteExpiration(expireTime.Value);
				}
				LocalCacheProvider.MemCache.Set(key, value, options);
			}
		}

		public bool Remove(string key)
		{
			LocalCacheProvider.MemCache.Remove(key);
			return true;
		}

		public bool Exists(string key)
		{
			return this.GetCache<object>(key) != null;
		}

		public void Dispose()
		{
			if (LocalCacheProvider.MemCache != null)
			{
				LocalCacheProvider.MemCache.Dispose();
			}
		}
	}
}
